/**
 * 账单中心服务
 * 基于LeanCloud进行应收单和对账单数据的CRUD操作
 */

import { dataAPI } from '@/http/leancloud';

// 应收单数据接口
export interface ReceivableData {
  objectId?: string;
  orderId?: any;
  cargoNo: string;
  orderNo: string;
  customerId?: string;
  customerName?: string;
  orderStatus: number;
  senderAddress: string;
  receiverAddress: string;
  settlementStatus: number; // 0未结算 1已结算
  settlementTime?: Date;
  reconciliationStatus: number; // 0未对账 1已对账
  reconciliationNo?: string;
  totalFreight: number;
  deliveryFee: number;
  unloadingFee: number;
  returnFee: number;
  transferFee: number;
  insuranceFee: number;
  packingFee: number;
  otherFee: number;
  cashPayment: number;
  pickupPayment: number;
  arrivalPayment: number;
  monthlyPayment: number;
  payableAmount: number;
  reconciledAmount: number;
  unreconciledAmount: number;
  invoiceStatus: number; // 0未开票 1已开票
  invoicedAmount: number;
  uninvoicedAmount: number;
  departureStationId?: string;
  arrivalStationId?: string;
  orderTime: Date;
  driverId?: string;
  driverPhone?: string;
  operator: string;
  senderName: string;
  senderPhone: string;
}

// 对账单数据接口
export interface ReconciliationData {
  objectId?: string;
  reconciliationNo: string;
  customerId?: string;
  customerName?: string;
  totalOrders: number;
  totalCargoQuantity: number;
  totalCargoVolume: number;
  totalCargoWeight: number;
  totalReceivable: number;
  totalReceived: number;
  balanceAmount: number;
  creator: string;
  createTime: Date;
  status: number; // 0草稿 1已生成 2已确认 3已结算
  confirmTime?: Date;
  settlementTime?: Date;
  senderName: string;
  senderPhone: string;
  senderAddress: string;
  orders: string[]; // 包含的订单ID列表
}

// 查询参数接口
export interface BillingQueryParams {
  cargoNo?: string;
  orderNo?: string;
  customer?: string;
  orderStatus?: number;
  settlementStatus?: number;
  reconciliationStatus?: number;
  startDate?: string;
  endDate?: string;
  shippingStation?: string;
  deliveryStation?: string;
  page?: number;
  pageSize?: number;
}

/**
 * 账单服务类
 */
export class BillingService {
  private static readonly RECEIVABLE_CLASS = 'Receivable';
  private static readonly RECONCILIATION_CLASS = 'Reconciliation';

  /**
   * 查询应收单列表
   */
  static async getReceivableList(params: BillingQueryParams = {}) {
    try {
      const query: any = {};
      
      // 构建查询条件
      if (params.cargoNo) {
        query.cargoNo = { $regex: params.cargoNo };
      }
      if (params.orderNo) {
        query.orderNo = { $regex: params.orderNo };
      }
      if (params.customer) {
        query.senderName = { $regex: params.customer };
      }
      if (params.orderStatus !== undefined) {
        query.orderStatus = params.orderStatus;
      }
      if (params.settlementStatus !== undefined) {
        query.settlementStatus = params.settlementStatus;
      }
      if (params.reconciliationStatus !== undefined) {
        query.reconciliationStatus = params.reconciliationStatus;
      }
      if (params.startDate && params.endDate) {
        query.orderTime = {
          $gte: new Date(params.startDate),
          $lte: new Date(params.endDate)
        };
      }

      const data = await dataAPI.query(this.RECEIVABLE_CLASS, query);
      return {
        success: true,
        data: data.map(this.formatReceivableData),
        total: data.length
      };
    } catch (error) {
      console.error('查询应收单列表失败:', error);
      return { success: false, error, data: [], total: 0 };
    }
  }

  /**
   * 查询对账单列表
   */
  static async getReconciliationList(params: BillingQueryParams = {}) {
    try {
      const query: any = {};
      
      // 构建查询条件
      if (params.customer) {
        query.customerName = { $regex: params.customer };
      }
      if (params.startDate && params.endDate) {
        query.createTime = {
          $gte: new Date(params.startDate),
          $lte: new Date(params.endDate)
        };
      }

      const data = await dataAPI.query(this.RECONCILIATION_CLASS, query);
      return {
        success: true,
        data: data.map(this.formatReconciliationData),
        total: data.length
      };
    } catch (error) {
      console.error('查询对账单列表失败:', error);
      return { success: false, error, data: [], total: 0 };
    }
  }

  /**
   * 结算应收单
   */
  static async settleReceivable(receivableId: string, settlementData?: {
    settlementAmount?: number;
    settlementNote?: string;
  }) {
    try {
      const updateData = {
        settlementStatus: 1,
        settlementTime: new Date(),
        ...settlementData
      };
      
      await dataAPI.save(this.RECEIVABLE_CLASS, {
        objectId: receivableId,
        ...updateData
      });
      
      return { success: true };
    } catch (error) {
      console.error('结算应收单失败:', error);
      return { success: false, error };
    }
  }

  /**
   * 生成对账单
   */
  static async generateReconciliation(receivableIds: string[], reconciliationData: {
    customerId?: string;
    customerName: string;
    creator: string;
  }) {
    try {
      // 获取应收单信息
      const receivables = await Promise.all(
        receivableIds.map(id => dataAPI.get(this.RECEIVABLE_CLASS, id))
      );
      
      // 计算统计信息
      const totalOrders = receivables.length;
      const totalReceivable = receivables.reduce((sum, item) => sum + (item?.payableAmount || 0), 0);
      const totalReceived = receivables.reduce((sum, item) => sum + (item?.reconciledAmount || 0), 0);
      
      // 生成对账单号
      const reconciliationNo = this.generateReconciliationNo();
      
      // 创建对账单
      const reconciliation = await dataAPI.save(this.RECONCILIATION_CLASS, {
        reconciliationNo,
        customerId: reconciliationData.customerId,
        customerName: reconciliationData.customerName,
        totalOrders,
        totalReceivable,
        totalReceived,
        balanceAmount: totalReceivable - totalReceived,
        creator: reconciliationData.creator,
        createTime: new Date(),
        status: 1,
        orders: receivableIds,
        senderName: receivables[0]?.senderName || '',
        senderPhone: receivables[0]?.senderPhone || '',
        senderAddress: receivables[0]?.senderAddress || ''
      });
      
      // 更新应收单的对账状态
      await Promise.all(
        receivableIds.map(id => 
          dataAPI.save(this.RECEIVABLE_CLASS, {
            objectId: id,
            reconciliationStatus: 1,
            reconciliationNo
          })
        )
      );
      
      return { success: true, data: reconciliation };
    } catch (error) {
      console.error('生成对账单失败:', error);
      return { success: false, error };
    }
  }

  /**
   * 确认对账单
   */
  static async confirmReconciliation(reconciliationId: string) {
    try {
      await dataAPI.save(this.RECONCILIATION_CLASS, {
        objectId: reconciliationId,
        status: 2,
        confirmTime: new Date()
      });
      
      return { success: true };
    } catch (error) {
      console.error('确认对账单失败:', error);
      return { success: false, error };
    }
  }

  /**
   * 结算对账单
   */
  static async settleReconciliation(reconciliationId: string, settlementData?: {
    settlementAmount?: number;
    settlementNote?: string;
  }) {
    try {
      const updateData = {
        status: 3,
        settlementTime: new Date(),
        ...settlementData
      };
      
      await dataAPI.save(this.RECONCILIATION_CLASS, {
        objectId: reconciliationId,
        ...updateData
      });
      
      return { success: true };
    } catch (error) {
      console.error('结算对账单失败:', error);
      return { success: false, error };
    }
  }

  /**
   * 删除对账单
   */
  static async deleteReconciliation(reconciliationId: string) {
    try {
      // 获取对账单信息
      const reconciliation = await dataAPI.get(this.RECONCILIATION_CLASS, reconciliationId);
      
      if (reconciliation?.status !== 0) {
        throw new Error('只能删除草稿状态的对账单');
      }
      
      // 删除对账单
      await dataAPI.delete(this.RECONCILIATION_CLASS, reconciliationId);
      
      // 重置相关应收单的对账状态
      if (reconciliation.orders) {
        await Promise.all(
          reconciliation.orders.map((orderId: string) =>
            dataAPI.save(this.RECEIVABLE_CLASS, {
              objectId: orderId,
              reconciliationStatus: 0,
              reconciliationNo: ''
            })
          )
        );
      }
      
      return { success: true };
    } catch (error) {
      console.error('删除对账单失败:', error);
      return { success: false, error };
    }
  }

  /**
   * 格式化应收单数据
   */
  private static formatReceivableData(item: any): ReceivableData {
    return {
      objectId: item.objectId,
      cargoNo: item.cargoNo || '',
      orderNo: item.orderNo || '',
      customerId: item.customerId,
      customerName: item.customerName || item.senderName || '',
      orderStatus: item.orderStatus || 0,
      senderAddress: item.senderAddress || '',
      receiverAddress: item.receiverAddress || '',
      settlementStatus: item.settlementStatus || 0,
      settlementTime: item.settlementTime ? new Date(item.settlementTime) : undefined,
      reconciliationStatus: item.reconciliationStatus || 0,
      reconciliationNo: item.reconciliationNo || '',
      totalFreight: item.totalFreight || 0,
      deliveryFee: item.deliveryFee || 0,
      unloadingFee: item.unloadingFee || 0,
      returnFee: item.returnFee || 0,
      transferFee: item.transferFee || 0,
      insuranceFee: item.insuranceFee || 0,
      packingFee: item.packingFee || 0,
      otherFee: item.otherFee || 0,
      cashPayment: item.cashPayment || 0,
      pickupPayment: item.pickupPayment || 0,
      arrivalPayment: item.arrivalPayment || 0,
      monthlyPayment: item.monthlyPayment || 0,
      payableAmount: item.payableAmount || 0,
      reconciledAmount: item.reconciledAmount || 0,
      unreconciledAmount: item.unreconciledAmount || 0,
      invoiceStatus: item.invoiceStatus || 0,
      invoicedAmount: item.invoicedAmount || 0,
      uninvoicedAmount: item.uninvoicedAmount || 0,
      orderTime: item.orderTime ? new Date(item.orderTime) : new Date(),
      driverId: item.driverId,
      driverPhone: item.driverPhone || '',
      operator: item.operator || '',
      senderName: item.senderName || '',
      senderPhone: item.senderPhone || ''
    };
  }

  /**
   * 格式化对账单数据
   */
  private static formatReconciliationData(item: any): ReconciliationData {
    return {
      objectId: item.objectId,
      reconciliationNo: item.reconciliationNo || '',
      customerId: item.customerId,
      customerName: item.customerName || '',
      totalOrders: item.totalOrders || 0,
      totalCargoQuantity: item.totalCargoQuantity || 0,
      totalCargoVolume: item.totalCargoVolume || 0,
      totalCargoWeight: item.totalCargoWeight || 0,
      totalReceivable: item.totalReceivable || 0,
      totalReceived: item.totalReceived || 0,
      balanceAmount: item.balanceAmount || 0,
      creator: item.creator || '',
      createTime: item.createTime ? new Date(item.createTime) : new Date(),
      status: item.status || 0,
      confirmTime: item.confirmTime ? new Date(item.confirmTime) : undefined,
      settlementTime: item.settlementTime ? new Date(item.settlementTime) : undefined,
      senderName: item.senderName || '',
      senderPhone: item.senderPhone || '',
      senderAddress: item.senderAddress || '',
      orders: item.orders || []
    };
  }

  /**
   * 生成对账单号
   */
  private static generateReconciliationNo(): string {
    const now = new Date();
    const dateStr = now.getFullYear().toString() +
                   (now.getMonth() + 1).toString().padStart(2, '0') +
                   now.getDate().toString().padStart(2, '0');
    const timeStr = now.getHours().toString().padStart(2, '0') +
                   now.getMinutes().toString().padStart(2, '0') +
                   now.getSeconds().toString().padStart(2, '0');
    return `RC${dateStr}${timeStr}`;
  }

  /**
   * 获取订单状态文本
   */
  static getOrderStatusText(status: number): string {
    const statusMap: { [key: number]: string } = {
      0: '待处理',
      1: '处理中',
      2: '已完成',
      3: '已取消'
    };
    return statusMap[status] || '未知状态';
  }

  /**
   * 获取结算状态文本
   */
  static getSettlementStatusText(status: number): string {
    const statusMap: { [key: number]: string } = {
      0: '未结算',
      1: '已结算'
    };
    return statusMap[status] || '未知状态';
  }

  /**
   * 获取对账状态文本
   */
  static getReconciliationStatusText(status: number): string {
    const statusMap: { [key: number]: string } = {
      0: '未对账',
      1: '已对账'
    };
    return statusMap[status] || '未知状态';
  }

  /**
   * 获取对账单状态文本
   */
  static getReconciliationBillStatusText(status: number): string {
    const statusMap: { [key: number]: string } = {
      0: '草稿',
      1: '已生成',
      2: '已确认',
      3: '已结算'
    };
    return statusMap[status] || '未知状态';
  }
}